package com.example.demo.ui.tree;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.demo.bese.BaseActivity;
import com.example.demo.databinding.ActivityMultiLevelTreeBinding;
import com.example.demo.model.BaseBean;
import com.example.demo.model.MultiChildrenBean;
import com.example.demo.ui.tree.adapter.MultiLevelTreeAdapter;
import com.example.demo.util.MyJson;
import com.example.library.utils.AssetsUtil;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author: xtxiaolu
 * @date: 2023/6/7
 * 描述: 多级树 不固定层级
 */
public class MultiLevelTreeActivity extends BaseActivity {
    private ActivityMultiLevelTreeBinding binding;
    private List<MultiChildrenBean> mChildren = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMultiLevelTreeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        String rqsJson = AssetsUtil.getAssetsJson(this,"MultiLevelTree.json");
        BaseBean data = MyJson.fromJson(rqsJson, BaseBean.class);
        mChildren = MyJson.fromJson(MyJson.toJson(data.getData()), new TypeToken<List<MultiChildrenBean>>() {
        }.getType());

        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        MultiLevelTreeAdapter treeAdapter = new MultiLevelTreeAdapter(this, mChildren);
        binding.recyclerView.setAdapter(treeAdapter);

        treeAdapter.setOnItemClickListener(new MultiLevelTreeAdapter.OnItemClickListener() {

            @Override
            public void onCheckClick(View v, int pos, MultiChildrenBean model) {
                System.err.println("tree is null");
                Toast.makeText(MultiLevelTreeActivity.this,"当前选择 "+model.getPathName(),
                        Toast.LENGTH_LONG).show();
            }

            @Override
            public void onOpenChildClick(View v, int pos, int tag, MultiChildrenBean model) {
                if (tag == 0){
                    if (model.getChildren() != null){ //如果有子集  就展开或者关闭
                        treeAdapter.setOpenOrClose(mChildren,pos);
                        treeAdapter.notifyDataSetChanged();
                    } else {  //没有子集  就选中
                        onCheckClick(v,pos,model);
                    }
                } else {
                    onCheckClick(v,pos,model);
                }
            }
        });
    }
}